<template>
    <div class="test-container">
        <div class="test-div">
            <button @click="startRecognition">开始语音识别</button>
            <button @click="stopRecognition" :disabled="!speechRecognition">停止识别</button>
            <div v-if="speechRecognition">
                识别状态: {{ recognizing ? '正在进行...' : '等待...' }}
            </div>
            <ul>
                <li v-for="result in results" :key="result.index">{{ result[0].transcript }}</li>
            </ul>
        </div>
    </div>
</template>
<script>
import { get, post } from '@/api';

export default {
    name: 'Test',
    components: {
    },
    data() {
        return {
            // 用于存储接收到的消息
            messages: [],
            messageString: "",
            speechRecognition: null,
            recognizing: false,
            results: []
        };
    },
    created() {
        // this.recognition = new webkitSpeechRecognition() || new SpeechRecognition(); // 兼容性处理
        // this.recognition.continuous = true; // 连续识别
        // this.recognition.onresult = this.handleResults; // 设置结果处理函数
        // this.recognition.onerror = event => {
        //     console.error('语音识别错误:', event.error);
        // };

        // this.recognition.onend = () => {
        //     console.log('语音识别结束');
        // };
    },
    mounted() {
        // 组件挂载后开始接收流式数据
        // this.getFetchData();
        // this.get_fetchData();
        // this.post_fetchData();
    },
    beforeDestroy() {
        // 组件销毁前，关闭EventSource连接
        if (this.eventSource) {
            this.eventSource.close();
        }
    },
    methods: {// 定义一个方法，用于调用后端API
        async get_fetchData() {
            let username = 'test';
            let password = '123456';
            try {
                const response = await get('/api/testget', { username, password });
                const responseData = response.data;
                console.log('Response Data:', responseData);
                // 这里可以添加更多的逻辑来使用响应数据
            } catch (error) {
                // 处理错误
                console.error('请求失败:', error);
            }
        },
        async post_fetchData() {
            const data = {
                username: '这是要提交的数据',
                password: '写成字典的形式'
            };
            post('api/testpost', data)
                .then(response => {
                    console.log(response.data); // 打印响应数据
                })
                .catch(error => {
                    console.error('Error during post request:', error);
                });
        },
        getFetchData() {
            // 后端流式API的URL，需要根据你的FastAPI后端设置
            const streamUrl = 'http://localhost:8000/api/testchat';

            // 创建EventSource连接
            const eventSource = new EventSource(streamUrl);

            eventSource.onmessage = event => {
                // 将接收到的数据添加到messages数组
                const jsonString = event.data.trim();
                // 使用JSON.parse()解析JSON字符串
                var data = JSON.parse(jsonString);
                // console.log('Received message:', data.id, data.chunk);
                this.messages.push(data.chunk);
                this.messageString = this.messages.join('');
            };

            eventSource.onerror = error => {
                console.error('EventSource error:', error);
                // 处理错误，例如关闭EventSource连接
                eventSource.close();
            };
        },
        startSpeech() {
            this.recognition.start(); // 开始语音识别
            alert('开始语音识别');
        },
        stopSpeech() {
            if (this.recognition) {
                this.recognition.stop();
            }
        },
        handleResults(event) {
            const current = event.resultIndex;
            const transcript = event.results[current][0].transcript;
            this.outputText = transcript; // 更新输出文本
        },
        startRecognition() {
            this.speechRecognition = new webkitSpeechRecognition() || new SpeechRecognition(); // 兼容性处理

            this.speechRecognition.continuous = true;
            this.speechRecognition.onresult = (event) => {
                this.results = event.results;
                this.recognizing = true;
            };

            this.speechRecognition.onend = () => {
                this.recognizing = false;
            };

            this.speechRecognition.start();
        },
        stopRecognition() {
            this.speechRecognition.stop();
            this.speechRecognition = null;
        },
    },
}
</script>
<style scoped>
.test-container {
    width: 100vw;
    padding: 0;
    margin: 0;
    overflow: hidden;
}

.test-div {
    width: 100vw;
    background-color: #e1f9f4;
}
</style>